<?php

namespace App\Listeners;

use App\Models\Share;
use App\Models\User;
use Illuminate\Auth\Events\Registered;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Support\Str;

class CreateShare implements ShouldQueue
{

    public function handle(Registered $event): void
    {
        /** @var User $user */
        $user = $event->user;

        $user->share()->create([
            'parent_id' => $user->others?->get('parent_id'),
            'code' => $this->code(),
        ]);
    }

    protected function code(): string
    {
        $code = Str::random(8);

        if (Share::query()->where('code', $code)->exists()) {
            return $this->code();
        }

        return $code;
    }
}
